# -*- coding: UTF-8 -*-
# 2023/11/26 23:24
import os.path
from threading import Thread

from ttkbootstrap import Button
from ttkbootstrap.scrolled import ScrolledFrame

from tools.get_configer import my_configer
from tools.get_logger import get_logger
from tools.pool_download_cover import pool_download_cover

configer = my_configer()
loger = get_logger()


class class_page_frame(ScrolledFrame):
    def __init__(self, cover_type: str, line_num, class_id_cover_url_name_save_path_list, **kwargs):
        super().__init__(**kwargs)

        self.line_num = line_num
        self.class_id_cover_url_name_save_path_list = class_id_cover_url_name_save_path_list
        self.cover_type = cover_type
        self.class_btn_list = list()  # 生成的所有按钮

        self.add_img_class()

        loger.info(f"{self.cover_type}壁纸窗口组件创建")

    def add_img_class(self):
        """
        以按钮图片形式添加图片到ScrolledFrame中
        """
        row = 0
        for column in range(len(self.class_id_cover_url_name_save_path_list)):
            class_id_cover_url_name_save_path = self.class_id_cover_url_name_save_path_list[column]

            # 创建组件并给组件添加img_id、img_url、save_path属性方便后面异步使用
            btn = Button(self, text=f"{class_id_cover_url_name_save_path[2]}")

            # 绑定属性方便线程池调用
            setattr(btn, "btn_img_id", class_id_cover_url_name_save_path[0])
            setattr(btn, "btn_img_url", class_id_cover_url_name_save_path[1])
            setattr(btn, "btn_name", class_id_cover_url_name_save_path[2])
            setattr(btn, "btn_cover_save_path", os.path.abspath(class_id_cover_url_name_save_path[3]))

            # 布局和拉伸策略
            if column % self.line_num == 0 and column != 0:
                row += 1
            btn.grid(row=row, column=column % self.line_num, ipadx=10, ipady=10)
            self.grid_rowconfigure(row, weight=1)
            self.grid_columnconfigure(column % self.line_num, weight=1)

            # 按钮加入列表
            self.class_btn_list.append(btn)

            loger.info(f"批量生成[{class_id_cover_url_name_save_path[0]},{class_id_cover_url_name_save_path[2]}]按钮!")

        thread_pool_download_thred = Thread(target=pool_download_cover, args=(self.class_btn_list,), daemon=True)
        thread_pool_download_thred.start()
